
function RefreshComments(id, user) {
  
  var text = "";
  // Retrieve list of comments
  var response = "" + SynchronousAjax("CommentQuery?t=" + Math.random() +
      "&type=getcommentids&id=" + id).split(",");
  var ids = response.split(',');
  
  var jumlah = 0;
  
  for (var i = 0; i < ids.length; ++i) {
    if (ids[i] == "") continue;
    jumlah += 1;
    text += "<li class='comment'>";
    text += "<ul>";
    text += "<li class='comment_header'>";
    
    // Get username and avatar
    var poster = SynchronousAjax("CommentQuery?t=" + Math.random() +
        "&type=getusername&id=" + ids[i]);
    var avatar = SynchronousAjax("UsernameQuery?t=" + Math.random() +
        "&type=getavatar&username=" + poster);
    text += '<img src="/snsdbook/avatar/' + avatar + '" height="42" width="42" />';
    text += '<a href=User?username=' + poster + '>' + poster + '</a>';
    text += '</li>';
    
    text += "<li class='comment_header'>";
    // Get time
    var timestamp = SynchronousAjax("CommentQuery?t=" + Math.random() +
        "&type=gettimestamp&id=" + ids[i]);
    text += ParseTime(timestamp) + " ago";
    text += "</li>";
    
    // Tombol delete kalo boleh
    if (poster == user) {
      text += "<li class='comment_header'>";
      text += "<button id='delete_button" + ids[i] + "' " +
        "onclick=\"DeleteComment('" + ids[i] + "', '" +
        user + "', '" + id + "')\">Delete</button>";
    }
    
    text += "<li class='comment_body'>";
    var body = SynchronousAjax("CommentQuery?t=" + Math.random() +
        "&type=getcontent&id=" + ids[i]);
    text += body;
    text += "</li>";
    text += "</ul>";
    text += "</li>";
  }
  
  document.getElementById("comment_list").innerHTML = text;
  ShowNumberOfComments(id);
}

function ShowNumberOfComments(id) {
  
  // Retrieve list of comments
  var response = "" + SynchronousAjax("CommentQuery?t=" + Math.random() +
      "&type=getcommentids&id=" + id).split(",");
  var ids = response.split(',');
  
  var jumlah = 0;
  
  for (var i = 0; i < ids.length; ++i) {
    if (ids[i] == "") continue;
    jumlah += 1;
  }
  
  document.getElementById("comment_count" + id).innerHTML = jumlah;
}

function DeleteComment(id, user, content_id) {
  // Ajax
  SynchronousAjax("CommentQuery?t=" + Math.random() +
      "&type=delete" + "&id=" + id, false);
  RefreshComments(content_id, user);
}

function AddComment(content_id, user) {
  var content = document.getElementById("comment_input").value;
  SynchronousAjax("CommentQuery?t=" + Math.random() +
      "&type=insert" + "&id=" + content_id +
      "&username=" + user +
      "&content=" + content, false);
  RefreshComments(content_id, user);
}
